package chapter1.bagqueuestack.example;

import edu.princeton.cs.algs4.StdIn;
import org.jetbrains.annotations.NotNull;

import java.util.Iterator;

/**
 * @author quanlinlin on 2018/12/1 23:22.
 * @version 1.0
 */
public class Queue<Item> implements Iterable<Item> {

    @NotNull
    @Override
    public Iterator<Item> iterator() {
        return null;
    }

    private Node first;

    private Node last;

    private int N;


    private class Node {
        Item item;
        Node next;
    }

    public boolean isEmpty() {
        return first == null;
    }

    public int size() {
        return N;
    }

    public void enqueue(Item item) {
        //向表尾添加元素
        Node oldlast = this.last;
        last = new Node();
        last.item = item;
        last.next = null;
        if (isEmpty()) {
            first = last;
        } else {
            oldlast.next = last;
        }
        N++;
    }

    public Item dequue() {
        //从表头删除元素
        Item item = first.item;
        first = first.next;
        if (isEmpty()) {
            last = null;
        }
        N--;
        return item;
    }

    public static void main(String[] args) {
        Queue<String> q = new Queue<>();
        while (!StdIn.isEmpty()) {
            String item = StdIn.readString();
            if (!item.equals("-")) {
                q.enqueue(item);
            } else if (!q.isEmpty()) {
                System.out.print(q.dequue() + " ");
            }
        }
        System.out.println("(" + q.size() + " left on queue)");
    }
}
